<template>
  <section>
     
    <!-- 面包屑 -->
     <breadcrumbs></breadcrumbs>
    <div class="top-box">
      <div class="top-item">
        <img src="../../assets/images/caigouzongzhichu.png" alt="" class="top-icon" />
        <div class="right-item-box">
          <p>
            <span class="fontTop">{{ xianshidata.purchaseMoneySum / 100 }}</span><br />
            <span class="fontText">总采购支出（元）</span>
          </p>
        </div>
      </div>
      <!-- <el-button type="primary" @click="addhouse">新增运营中心</el-button> -->
    </div>
    <!-- 查询条件 -->
    <el-form ref="searchForm" :model="searchForm" label-width="100px" inline class="demo-form-inline" size="small" style="border-bottom: 1px solid #f6f6f6">
      <el-form-item label="商品名称" prop="">
        <el-input v-model="searchForm.goodsName" placeholder="请输入商品名称"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <btns @exec="exec"></btns>
    <div class="data-container scroll-table">
      <div>
        <div class="ind-title lh50 f16">采购单列表</div>
      </div>
      <el-table :data="tableData" style="width: 100%" row-key="dictId" border @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="80"> </el-table-column>
        <el-table-column label="序号" prop="index" type="index" width="100px"></el-table-column>
        <el-table-column prop="goodsName" width="300" label="商品名称">
        </el-table-column>

        <el-table-column prop="purchaseAllMoney" width="300" label="进货总金额(元)">
          <template slot-scope="scope">
            <p v-if="
                scope.row.purchaseAllMoney == null ||
                scope.row.purchaseAllMoney == undefined
              ">
              0
            </p>
            <p v-else>{{ scope.row.purchaseAllMoney / 100 }}</p>
          </template>
        </el-table-column>

        <el-table-column prop="purchaseNum" width="300" label="采购数">
        </el-table-column>

        <el-table-column prop="state" width="100" label="状态">
          <template slot-scope="scope">
            <p v-if="scope.row.state == 1">已入库</p>
            <p v-if="scope.row.state == 2">未入库</p>
          </template>
        </el-table-column>

        <el-table-column prop="remark" width="300" label="备注">
        </el-table-column>

        <el-table-column prop="addtime" width="500" label="添加时间">
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- <el-dialog title="编辑分类"
               :visible.sync="dialogEditFormVisible">
      <el-form :model="editForm"
               label-width="120px"
               ref="editForm"
               :rules="rules">

          <el-form-item label="分类名称"
                      prop="goodsName">
          <el-input v-model="editForm.goodsName"
                    maxlength="25"
                    show-word-limit
                    autocomplete="off"></el-input>
        </el-form-item>

        
          <el-form-item label="排序"
                      prop="purchaseAllMoney">
          <el-input v-model="editForm.purchaseAllMoney"
                    maxlength="25"
                    type="number"
                    show-word-limit
                    autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editQuestions('editForm')">确 定</el-button>
      </div>
    </el-dialog> -->

    <el-dialog title="编辑采购商品" :visible.sync="dialogEditFormVisible">
      <el-form :model="editForm" label-width="120px" ref="editForm" :rules="rules">
        <el-form-item label="商品名称" prop="goodsName">
          <el-select v-model="editForm.goodsId" placeholder="请选择商品名称">
            <el-option v-for="(item, i) in shangpindata1" :key="i" :label="item.goodsName" :value="item.goodsId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="进货总金额(元）" prop="purchaseAllMoney">
          <el-input v-model="editForm.purchaseAllMoney" maxlength="25" type="number" show-word-limit autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="采购数量" prop="purchaseNum">
          <el-input v-model="editForm.purchaseNum" maxlength="25" type="number" show-word-limit autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" maxlength="50" show-word-limit autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editQuestions('editForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加采购商品" :visible.sync="dialogCreateFormVisible">
      <el-form :model="createForm" label-width="120px" ref="createForm" :rules="rules">
        <el-form-item label="商品名称" prop="goodsId">
          <el-select v-model="createForm.goodsId" placeholder="请选择商品名称">
            <el-option v-for="(item, i) in shangpindata1" :key="i" :label="item.goodsName" :value="item.goodsId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="进货总金额(元)" prop="purchaseAllMoney">
          <el-input v-model="createForm.purchaseAllMoney" maxlength="25" type="number" show-word-limit autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="采购数量" prop="purchaseNum">
          <el-input v-model="createForm.purchaseNum" maxlength="25" type="number" show-word-limit autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="createForm.remark" maxlength="50" show-word-limit autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProblem('createForm')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import btns from "@/components/btns.vue";
import Editor from "@/components/edit";
import breadcrumbs from "@/components/breadcrumbs.vue";
import { unitPriceValidate } from "../../utils/tool";
export default {
  components: {
    btns,
    Editor,
    breadcrumbs,
  },
  data() {
    var telValidate = (rule, value, callback) => {
      if (value != null && value != "") {
        var tel = /^0\d{2,3}-?\d{7,8}$/;
        var phone = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if (value.length == 11) {
          //手机号码
          if (phone.test(value)) {
            console.log(value);
            return true;
          }
        } else if (value.length == 13 && value.indexOf("-") != -1) {
          //电话号码
          if (tel.test(value)) {
            console.log(value);
            return true;
          }
        }
        callback("请输入正确的电话号码！");
      } else {
        callback();
      }
    };
    return {
      shangpindata: [],
      xianshidata: [],
      searchForm: {
        goodsName: "",
      },
      shangpindata1: [],
      state: "",
      tableSelection: [],
      dialogEditFormVisible: false,
      tableData: [],
      editForm: {},
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogCreateFormVisible: false,
      createForm: {},
      rules: {
        goodsId: [
          { required: true, message: "请选择商品名称", trigger: "blur" },
        ],
        purchaseAllMoney: [
          { required: true, message: "请输入采购总金额", trigger: "blur" },
          { validator: unitPriceValidate, trigger: "blur" },
        ],
        purchaseNum: [
          { required: true, message: "请输入采购数量", trigger: "blur" },
        ],
        goodsName: [
          { required: true, message: "请选择商品名称", trigger: "blur" },
        ],
      },
      formLabelWidth: "120px",
      addfile: "",
      importFileUrl: this.GLOBAL.imgBaseUrl,
    };
  },
  created() {
    this.xianshi();
    this.shangpinlist1();
    this.getList();
  },
  methods: {
    shangpinlist() {
      this.$api.integral.huoqushangpinlist({}).then((d) => {
        if (d.code == 200) {
          this.shangpindata = d.data;
        }
      });
    },
    shangpinlist1() {
      this.$api.integral
        .huoqushangpinlist1({
          state: 1,
        })
        .then((d) => {
          if (d.code == 200) {
            this.shangpindata1 = d.data;
          }
        });
    },
    xianshi() {
      this.$api.integral.fanhuixianshi({}).then((d) => {
        if (d.code == 200) {
          this.xianshidata = d.data;
        }
      });
    },

    // update () {
    //     if (this.tableSelection.length != 1) {
    //         this.$message.error('请选中一行数据');
    //         return
    //     }
    //     let id = this.tableSelection[0].bannerId;
    //     this.$router.push({
    //         path: `/banner/edit`,
    //         query: { id: id }
    //     })
    // },
    enable() {
      if (this.tableSelection.length != 1) {
        this.$message.error("请选中一行数据");
        return;
      }
      var demo = this.tableSelection[0];
      if (demo.bannerStatus == 1) {
        this.$message.error("该数据已启用");
        return;
      }
      this.$confirm("此操作将启用该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.banner
          .status({
            bannerIds: demo.bannerId,
            status: 1,
          })
          .then((d) => {
            if (d.code == 1) {
              this.$message.success("启用成功");
              this.loadData();
            } else {
              this.$message.error(d.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          });
      });
    },
    disable() {
      if (this.tableSelection.length != 1) {
        this.$message.error("请选中一行数据");
        return;
      }
      var demo = this.tableSelection[0];
      if (demo.bannerStatus == 0) {
        this.$message.error("该数据已禁用");
        return;
      }
      this.$confirm("此操作将禁用该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.banner
          .status({
            bannerIds: demo.bannerId,
            status: 0,
          })
          .then((d) => {
            if (d.code == 1) {
              this.$message.success("禁用成功");
              this.loadData();
            } else {
              this.$message.error(d.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          });
      });
    },
    editQuestions(formName) {
      this.$api.integral
        .updatecaigou({
          purchaseId: this.tableSelection[0].integralGoodsPurchaseId,
          goodsId: this.editForm.goodsId,
          purchaseAllMoney: parseInt(this.editForm.purchaseAllMoney * 100),
          purchaseNum: this.editForm.purchaseNum,
          remark: this.editForm.remark,
        })
        .then((d) => {
          if (d.code == 200) {
            this.$message.success("修改成功");
            this.dialogEditFormVisible = false;
            this.getList();
          }
        });
    },
    getList() {
      this.$api.integral
        .caigoulist({
          current: this.currentPage,
          size: this.pageSize,
          goodsName: this.searchForm.goodsName,
        })
        .then((d) => {
          if (d.code == 200) {
            this.tableData = d.data;
            this.total = d.totalCount;
          }
        });
    },
    add(e) {
      this.dialogCreateFormVisible = true;

      this.createForm = {
        goodsName: "",
        goodsId: "",
        purchaseAllMoney: "",
        purchaseNum: "",
        remark: "",
      };
    },
    addProblem(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$api.integral
            .addcaigou({
              goodsId: this.createForm.goodsId,
              purchaseAllMoney: parseInt(this.createForm.purchaseAllMoney * 100),
              purchaseNum: this.createForm.purchaseNum,
              remark: this.createForm.remark,
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message.success("添加成功");
                this.dialogCreateFormVisible = false;
                this.getList();
              }
            });
        }
      })

    },
    //打开新增模态框

    //打开编辑模态框
    update() {
      console.log("进入编辑");
      if (this.tableSelection.length != 1) {
        this.$message.error("请选中一行数据");
        return;
      }

      this.editForm = {
        goodsId: this.tableSelection[0].goodsId,
        goodsName: this.tableSelection[0].goodsName,
        purchaseAllMoney: this.tableSelection[0].purchaseAllMoney / 100,
        purchaseNum: this.tableSelection[0].purchaseNum,
        remark: this.tableSelection[0].remark,
      };

      this.state = this.tableSelection[0].state;
      this.isShowEditedit = true;
      this.isShowFengEdit = true;
      this.isShowProductListEdit = false;
      this.isShowGoodsListEdit = false;

      if (this.tableSelection[0].state == 1) {
        this.$message.error("该条商品已入库，不能修改");
        return;
      }
      // console.log(this.editForm);
      this.dialogEditFormVisible = true;
    },

    //入库
    deliveryback() {
      if (this.tableSelection.length != 1) {
        this.$message.error("请选中一行数据");
        return;
      }
      if (this.tableSelection[0].state == 1) {
        this.$message.error("该条商品已入库，不能入库");
        return;
      }
      this.$confirm("确认要该商品入库吗, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.integral
            .enablecaigou({
              purchaseIds: this.tableSelection[0].integralGoodsPurchaseId,
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message.success("入库成功");
                this.getList();
              } else {
                this.$message.error(d.msg);
              }
            });
          // console.log(this.tableSelection[0].enable);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //删除数据
    del() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选中一行数据");
        return;
      }
      let stateArr = this.tableSelection.map((e) => {
        return e.state;
      });
      let s = new Set(stateArr);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] == 1) {
        this.$message.error("该条商品已入库，不能删除");
        return;
      }
      this.$confirm("确认要删除该商品吗, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = this.tableSelection.map(e => {
            return e.integralGoodsPurchaseId
          })
          this.$api.integral
            .delcaigou({
              purchaseId: ids.join(','),
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message.success("删除成功");
                this.getList();
              } else {
                this.$message.error(d.msg);
              }
            });
          // console.log(this.tableSelection[0].enable);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //启用
    enable() { },
    //禁用
    disable() { },
    search() {
      console.log("search");
      this.getList();
    },

    exec(fun) {
      if (this[fun]) {
        this.funTit = fun;
        this[fun]();
      } else {
        this.$message.error("方法未定义");
      }
    },

    handleReset() {
      this.searchForm = {
        goodsName: "",
        title: "",
        endTime: "",
        addTime: "",
      };

      this.search();
    },
    tableSelectionChange(val) {
      this.tableSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList(this.currentPage, val);
      // eslint-disable-next-line no-console
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList(val, this.pageSize);
      // eslint-disable-next-line no-console
      // console.log(`当前页: ${val}`);
    },
  },
};
</script>

<style lang="scss" scoped>
.fontText {
  font-size: 20px;
}

.fontTop {
  font-size: 40px;
}

.top-box {
  width: 35%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.top-item {
  border: 1px rgb(189, 185, 185) solid;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  padding: 20px;

  .top-icon {
    width: 35%;
    height: 35%;
  }

  .right-item-box {
    text-align: center;
    margin-left: 20px;
  }
}
</style>